//
//  UIProgressView.swift
//  进度视图
//
//  Created by cxc on 15/7/6.
//  Copyright © 2015年 rockcxc. All rights reserved.
//

import UIKit
import SDWebImage

class CCImageView: UIImageView {
    
    var progress:CGFloat = 0 {
        didSet{
            if progress > 0{
                progressView.progress = progress
                progressView.addSubview(label)
                label.center = progressView.center
                label.text = String(format:"%.0f%%", progress*100)
            }
        }
    }
    
    private lazy var progressView:CCProgressView = {[unowned self] in
        let v = CCProgressView()
        self.addSubview(v)
        v.ff_Fill(self)
        return v
    }()
    private lazy var label: UILabel = {
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(8)
        l.textAlignment = NSTextAlignment.Center
        l.textColor = UIColor.greenColor()
        l.bounds = CGRect(x: 0, y: 0, width: 22, height: 22)
        return l
    }()
    
    /// 嵌套的私有类，仅供UIProgressView使用
    private class CCProgressView: UIView {
        var progress:CGFloat = 0 {
            didSet{
                setNeedsDisplay()
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = UIColor.clearColor()
        }
        
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        override func drawRect(rect: CGRect) {
            let r = min(rect.width, rect.height)*0.4
            let centerP = CGPoint(x: rect.width*0.5, y: rect.height*0.5)
            let ovalRect = CGRect(x: centerP.x - r , y: centerP.y - r, width: 2*r, height: 2*r)
            
            let path1 = UIBezierPath(ovalInRect: ovalRect)
            UIColor(white: 1.0, alpha: 0.5).setFill()
            path1.fill()
            
            let startAngle = CGFloat(-M_PI_2)
            let endAngle = CGFloat(M_PI*2) * progress + startAngle
            
            let path2 = UIBezierPath(arcCenter: centerP, radius: r, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path2.addLineToPoint(centerP)
            path2.closePath()
            UIColor(white: 0.0, alpha: 0.5).setFill()
            path2.fill()
        }

    }
  
   
}
